package com.winter.util.serializer;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import org.apache.commons.lang3.ArrayUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 描述：使用Kryo 实现序列化
 *
 * @author Yongge
 * @version 1.0
 * @date 2017-04-29
 **/
public class KryoSerializer implements Serializer {
    private static final Kryo kryo = new Kryo();

    @Override
    public byte[] serialize(Object object) throws IOException {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();
             Output output = new Output()) {
            kryo.writeClassAndObject(output, object);
            output.flush();
            return os.toByteArray();
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws IOException {
        return deserialize(bytes, Object.class);
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {

        if (ArrayUtils.isNotEmpty(bytes)) {
            try (ByteArrayInputStream is = new ByteArrayInputStream(bytes);
                 Input input = new Input(is)) {
                return kryo.readObject(input, clazz);
            }
        }
        return null;
    }
}
